package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.CheckTypeDao;
import com.wlhse.entity.CheckTypePojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.CheckTypeService;
import com.wlhse.util.SortCodeUtil;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CheckTypeServiceImpl implements CheckTypeService {

    @Resource
    private CheckTypeDao checkTypeDao;

    @Resource
    private SortCodeUtil sortCodeUtil;

    //根据ID获取单条记录
    @Override
    public String queryById(Integer id) {
        return NR.r(CodeDict.CODE_MESSAGE_DATA, 0, 0, checkTypeDao.queryCheckTypeById(id), null, 0, 0);
    }

    @Override
    public String query(String checkTypeName, int pageIdx, int pageSize, String type) {
        if ("all".equals(type))
            return NR.r(checkTypeDao.queryCheckByName(checkTypeName));
        int total = checkTypeDao.queryTotal(checkTypeName);
        PageHelper.startPage(pageIdx, pageSize);
        List<CheckTypePojo> list = checkTypeDao.queryCheckByName(checkTypeName);
        return NR.r(list, total, pageIdx);
    }

    @Override
    @Transactional
    public String addCheckType(CheckTypePojo checkTypePojo) {
        String maxString = checkTypeDao.getMaxString();
        if (StringUtils.isNotBlank(maxString)) {
            String maxCodeString = sortCodeUtil.getMaxCodeString(maxString);
            checkTypePojo.setCheckTypeCode(maxCodeString);
        } else {
            checkTypePojo.setCheckTypeCode("0001");
        }
        if (checkTypeDao.addCheckType(checkTypePojo) <= 0)
            throw new WLHSException("新增失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String deleteCheckType(int checkTypeId) {
        if (checkTypeDao.deleteCheckType(checkTypeId) <= 0)
            throw new WLHSException("删除失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String updateCheckType(CheckTypePojo checkTypePojo) {
        if (checkTypeDao.updateCheckType(checkTypePojo) <= 0)
            throw new WLHSException("更新失败");
        return NR.r();
    }
}
